<template>
  <div>
    <van-popup v-if="loading" v-model:show="localCtaShow" position="bottom">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
              v-model="formParam.data.email"
              name="email"
              label="邮箱"
              placeholder="请输入您的邮箱"
              clearable
              :required="true"
              :rules="rules.email">
          </van-field>
          <van-field
              name="mobile_code"
              v-model="formParam.data.email_code"
              label="验证码"
              placeholder="请输入验证码"
              clearable
              type="number"
              :required="true"
              :rules="rules.email_code"
          >
            <!-- 自定义右侧按钮 -->
            <template #button>
              <van-button
                  type="primary"
                  size="small"
                  @click="dealSendEmailCode"
                  :disabled="countEmailDown > 0 || !isEmailValid">
                {{ countEmailDown > 0 ? countEmailDown + 's后重发' : '发送验证码' }}
              </van-button>
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button block type="primary" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted,computed,onUnmounted} from 'vue';
import { emailDownload, ctaFormSubmit} from "@/api/cta";
import { ctaSendEmailCode } from "@/api/mail";
import { sendContent } from "@/api/mail";
import {useRoute} from "vue-router";
import {showFailToast, showSuccessToast} from "vant";

const props = defineProps({
  omniUserUuid: {
    type: String,
    required: true
  },
  ctaUuid: {
    type: String,
    required: true
  },
  sceneType: String,
  sceneUuid: String,
  ctaShow: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["updateCtaShow"]);
const loading = ref<boolean>(false)

const route = useRoute();
const aggListUuid = route.params.aggListUuid as string;
const pushId = route.query.pushId as string;


const localCtaShow = computed({
  get() {
    return props.ctaShow;
  },
  set(value) {
    emit('updateCtaShow', value);
  }
});


onMounted(() => {
  console.log("加载CtaWechat")
  getCtaStatus();
});

const getCtaStatus = async () => {
  try {
    const response = await emailDownload({
      omni_user_uuid: props.omniUserUuid,
      content_uuid: props.sceneUuid,
      push_uuid:pushId
    });
    if(response.data.email){
      if(response.data.send){
        showSuccessToast('发送成功');
      }else{
        showFailToast('发送失败');
      }
    }else{
      loading.value = true
    }
  } catch (e) {
    console.error(e);
  }
}




const formParam = ref({
  omni_user_uuid:props.omniUserUuid,
  agg_uuid:aggListUuid,
  cta_uuid:props.ctaUuid,
  entity_type:props.sceneType,
  entity_uuid:props.sceneUuid,
  data:{
    email:'',
    email_code:'',
  }
});

const onSubmit = () => {
  try {
    ctaFormSubmit(formParam.value).then((response) => {
      if(response.data?.uuid !== undefined){
        //发送邮件
        sendEmailContent()
        emit("updateCtaShow");
      }
    })
  } catch (e) {
    console.log(e);
  } finally {

  }
};

const rules = {
  email: [
    { required: true, message: '请填写电子邮件地址' },
    { pattern: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, message: '请输入有效的电子邮件地址' }
  ],
  email_code:[
    { required: true, message: '请填写手机验证码' },
    { pattern: /^\d{6}$/, message: '手机验证码必须是6位数字'}
  ]
};




const countEmailDown = ref(0);
const dealSendEmailCode = () => {
  sendEmailCode()
  // 开始倒计时
  countEmailDown.value = 60;
  const timer = setInterval(() => {
    if (countEmailDown.value > 0) {
      countEmailDown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};
const isEmailValid = computed(() => {
  return formParam.value.data.email && formParam.value.data.email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/);
});
const sendEmailCode = () => {
  try {
    ctaSendEmailCode({
      email:formParam.value.data.email
    }).then((response) => {
      if(response.data.status){
        showSuccessToast('发送成功');
      }
    })
  } catch (e) {
    console.log(e);
  } finally {

  }
};
const sendEmailContent = () => {
  try {
    sendContent({
      omni_user_uuid:props.omniUserUuid,
      content_uuid:props.sceneUuid,
      push_uuid:pushId
    }).then((response) => {
      if(response.data.status){
        showSuccessToast('发送成功');
      }
    })
  } catch (e) {
    console.log(e);
  } finally {

  }
};


onUnmounted(() => {
  console.log("销毁CtaWechat")
});

</script>

<style scoped>
</style>
